<?php

declare(strict_types=1);

namespace App\AdminApi\Module\System\Service;

use App\AdminApi\Module\System\Enums\ResourcesCateState;
use App\AdminApi\Module\System\Traits\ConfigureTraits;
use App\Common\Model\System\ResourceModel;
use App\Sys;
use Exception;
use Hyperf\Database\Model\Builder;
use League\Flysystem\FilesystemException;
use Zms\AdminElementPlus\FormCreate\FormItem;
use Zms\Basics\BasicsServe;
use Zms\Service\Uploader;
use Zms\Unit\Is;
use Zms\Validate\Type;

/**
 * 资源服务层
 * Class BannerService
 */
class ResourcesService extends BasicsServe
{
    use ConfigureTraits;

    /**
     * @return ResourceModel::class
     */
    public static function model(): string
    {
        return ResourceModel::class;
    }

    public function getUploaderFormRule($configure): array
    {
        $rules = [];
        foreach (ResourcesCateState::Datas(ResourcesCateState::TAG['TYPE']) as $item) {
            $rules[] = FormItem::Labels($item['value'], "{$item['label']}上传", $configure[$item['value']] ?? [])->hint("允许上传的{$item['label']}格式,如:jpg,不设置代表不限制")->limit(200);
        }
        return $rules;
    }


    /**
     * 会员配置验证
     * @return array
     */
    public function getUploaderValidateRule(): array
    {
        $rules = [];
        $labels = [];
        foreach (ResourcesCateState::Datas(ResourcesCateState::TAG['TYPE']) as $item) {
            $rules[] = [$item['value'], Type::LIST, 'type' => 'string', 'type_error' => "{label}设置格式错误"];
            $labels[$item['value']] = $item['label'];
        }
        return [
            'rule' => $rules,
            'label' => $labels
        ];
    }

    /**
     * 资源名称搜索
     * @param Builder $query
     * @param $value
     * @author 竹林风@875384189 2021/9/8 10:22
     */
    public function searchName(Builder $query, $value): void
    {
        if (Is::notEmpty($value)) {
            $query->where('name', 'LIKE', "%$value%");
        }
    }

    /**
     * 删除资源
     * @param array $where
     * @return int
     */
    public function removeResources(array $where): int
    {
        $resources = $this->search($where)->get();
        if (count($resources) === 0) {
            return 0;
        }
        $success = 0;
        /**
         * @var ResourceModel $item
         */
        $uploader = Sys::container(Uploader::class);
        foreach ($resources as $item) {
            try {
                $uploader->drive($item->drive)->delete($item->path);
                $item->delete();
                $success++;
            } catch (Exception|FilesystemException $exception) {
                Sys::log('exceptions', 'upload')->error($exception->getMessage(), [
                    'exceptions' => ['file' => $exception->getFile(), 'line' => $exception->getLine(), 'class' => $exception::class]
                ]);
                continue;
            }
        }
        return $success;
    }
}